/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Servlet;

import Config.Constants;
import DAO.UserDAO;
import DTO.CommentDTO;
import DTO.OrderDTO;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import productJAXB.generate.ProductList;
import productJAXB.generate.Products;
import sample.utils.XMLUtils;

/**
 *
 * @author minhtrungn
 */
public class Controller extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        //response.setContentType("text/xml");
        request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        String user = (String) session.getAttribute("USER");
        String role = (String) session.getAttribute("ROLE");
        String action = request.getParameter("btnAction");
        UserDAO userDAO = new UserDAO();
        String url = Constants.MainPage;

        boolean isAjax = false;

        try {
            if (action.equals("userAjax")) {// check username is exist
                isAjax = true;
                String username = request.getParameter("username");
                boolean checkUser = userDAO.CheckUser(username);
                String text = "";
                if (checkUser) {
                    text = "Tài khoản " + " " + username + " " + "Đã tồn tại. Vui lòng thử lại!";
                } else {
                    text = "";
                }
                response.setContentType("text/plain");
                response.setCharacterEncoding("UTF-8");
                out.write(text);
            } else if (action.equals("commentAjax")) {
                String contentComment = request.getParameter("comment");
                long productID = Long.parseLong(request.getParameter("productid"));
                boolean rsInsert = userDAO.InsertComment(contentComment, user, productID);
                if (rsInsert) {
                    List<CommentDTO> listComment = new ArrayList();
                }
            } else if (action.equals("Register")) {
                String fullname = request.getParameter("txtFullname");
                String username = request.getParameter("txtUsername");
                String password = request.getParameter("txtPassword");
                String email = request.getParameter("txtEmail");
                String address = request.getParameter("txtAddress");
                String phone = request.getParameter("txtPhone");
                String selectgender = request.getParameter("selectGender");
                boolean checkUser = userDAO.CheckUser(username);
                if (checkUser) {
                    request.setAttribute("username", "Tài khoản" + username + " đã tồn tại. Vui lòng thử lại");
                    url = Constants.RegisterPage;
                } else {
                    boolean gender = false;
                    if (selectgender.equals("male")) {
                        gender = true;
                    }
                    boolean regist = userDAO.register(username, password, fullname, gender, email, phone, address);
                    if (regist == true) {
                        request.setAttribute("registSuccess", "Đăng kí thành công");
                    } else {
                        request.setAttribute("registSuccess", "Đăng kí không thành công");
                    }

                    url = Constants.RegisterPage;
                }

            } else if (action.equals("home")) {
                String context = getServletContext().getRealPath("/");
                userDAO.MarshallingProducts(context);
                session.setAttribute("currPage", "home");
                url = Constants.MainPage;
            } else if (action.equals("register")) {
                session.setAttribute("currPage", "regist");
                url = Constants.RegisterPage;
            } else if (action.equals("about")) {
                session.setAttribute("currPage", "about");
                url = Constants.AboutPage;
            } else if (action.equals("shoppingCart")) {
                session.setAttribute("currPage", "shoppingCart");
                url = Constants.shoppingCart;
            } else if (action.equals("CheckOut")) {
                String productList = request.getParameter("ProductListCheckOut");
                String adressDelivery = request.getParameter("adressDelivery");
                String addressOfCustomer = UserDAO.AddressToDelivery(user);
                List order = new ArrayList();
                String[] product = productList.split("\\.");
                for (int i = 0; i < product.length; i++) {
                    //int i = 0;
                    //while (i < product.length) { debug cho no vo cho nay coi
                    OrderDTO tmp = new OrderDTO();
                    String productInfo[] = product[i].split("\\,");
                    int id = Integer.parseInt(productInfo[3]);
                    long price = Long.parseLong(productInfo[1]);
                    int quantity = Integer.parseInt(productInfo[2]);
                    long total = quantity * price;
                    tmp.setProductID(id);
                    tmp.setPrice(price);
                    tmp.setQuantity(quantity);
                    tmp.setProductTotal(total);
                    order.add(tmp);
                }
//                long id = Long.parseLong(request.getParameter("idProduct"));
//                long price = Long.parseLong(request.getParameter("priceProduct"));
//                int quantity = Integer.parseInt(request.getParameter("quantityProduct"));
                long orderTotal = Long.parseLong(request.getParameter("totalCheckOut"));
                if (user == null || user == "") {
                    request.setAttribute("errorCheckOut", "Vui lòng đăng nhập trước khi mua hàng");
                    url = Constants.shoppingCart;

                } else {
                    // boolean rs = userDAO.CheckOut(id, user, orderTotal, quantity, price,total);
                    boolean rs;
                    if (adressDelivery.equals("")) {
                        rs = UserDAO.CheckOut(order, orderTotal, user, addressOfCustomer);
                    } else {
                        rs = UserDAO.CheckOut(order, orderTotal, user, adressDelivery);
                    }
                    if (rs) {
                        url = Constants.MainPage;
                    }
                }

            } else if (action.equals("orderList")) {
                List<OrderDTO> rs = userDAO.OrderList(user);
                request.setAttribute("orderList", rs);
                request.setAttribute("currPage", "orderPage");
                url = Constants.OrderPage;
            } else if (action.equals("orderDetail")) {
                long orderID = Long.parseLong(request.getParameter("orderID"));
                List<OrderDTO> orderDetail = userDAO.orderDetail(orderID);
                //ServletOutputStream sos = response.getOutputStream();
                //userDAO.MarshallingOrderDetail(orderID, sos);
                List<OrderDTO> rs = userDAO.OrderList(user);
                request.setAttribute("orderList", rs);
                request.setAttribute("orderID", orderID);
                request.setAttribute("orderDetail", orderDetail);
                //response.setContentType("text/xml;charset=UTF-8");
                //sos.flush();
                url = Constants.OrderPage;
            } else if (action.equals("search")) {
                session.setAttribute("currPage", "search");
                String search = request.getParameter("txtSearch");

                String webPath = getServletContext().getRealPath("/");
                String filePath = webPath + "WEB-INF/productList.xml";
                Document doc = XMLUtils.buildDOMTree(filePath);
                XPathFactory xpf = XPathFactory.newInstance();
                XPath xpath = xpf.newXPath();

                String paramFilter = request.getParameter("paramFilter");
                String exp = "";
                if (paramFilter.equals("search")) {
                    if (search == null || search == "") {
                        request.setAttribute("searchError", "Không có sản phẩm nào cho từ khóa này.");
                        url = Constants.Search;
                        RequestDispatcher rd = request.getRequestDispatcher(url);
                        rd.forward(request, response);
                    }
                    exp = "//product[productName[contains(translate(text(),'aăâbcdđeêghiklmnoôơpqrstuưvxyzwàáâãèéêìíòóôõùúĩũơưạảấầẩẫậắằẳẵặẹẻẽềềểễệỉịọỏốồổỗộớờởỡợụủứừỬỮỰửữựỳỵỷỹ','AĂÂBCDĐEÊGHIKLMNOÔƠPQRSTUƯVXYZWÀÁÂÃÈÉÊÌÍÒÓÔÕÙÚĨŨƠƯẠẢẤẦẨẪẬẮẰẲẴẶẸẺẼỀỀỂỄỆỈỊỌỎỐỒỔỖỘỚỜỞỠỢỤỦỨỪỲỴÝỶỸ'),translate('" + search + "','aăâbcdđeêghiklmnoôơpqrstuưvxyzwàáâãèéêìíòóôõùúĩũơưạảấầẩẫậắằẳẵặẹẻẽềềểễệỉịọỏốồổỗộớờởỡợụủứừỬỮỰửữựỳỵỷỹ ','AĂÂBCDĐEÊGHIKLMNOÔƠPQRSTUƯVXYZWÀÁÂÃÈÉÊÌÍÒÓÔÕÙÚĨŨƠƯẠẢẤẦẨẪẬẮẰẲẴẶẸẺẼỀỀỂỄỆỈỊỌỎỐỒỔỖỘỚỜỞỠỢỤỦỨỪỲỴÝỶỸ'))]]";
                } else if (paramFilter.equals("4woman")) {
                    exp = "//product[genderProduct = 'false']";
                    session.setAttribute("currPage", "4woman");
                } else if (paramFilter.equals("4man")) {
                    exp = "//product[genderProduct = 'true']";
                    session.setAttribute("currPage", "4man");
                } else {
                    exp = "//product[categoryID = '" + paramFilter + "']";
                }
                NodeList result = (NodeList) xpath.evaluate(exp, doc, XPathConstants.NODESET);
                System.out.println("tettt" + result);
                List listProduct = new ArrayList();
                for (int i = 0; i < result.getLength(); i++) {
                    Node node = result.item(i);
                    String cateID = node.getChildNodes().item(1).getTextContent();
                    String desc = node.getChildNodes().item(3).getTextContent();
                    String price = node.getChildNodes().item(5).getTextContent();
                    String pID = node.getChildNodes().item(7).getTextContent();
                    String img = node.getChildNodes().item(9).getTextContent();
                    String pName = node.getChildNodes().item(11).getTextContent();
                    //TestDTO product = new TestDTO();
                    ProductList product = new ProductList();
                    //System.out.println("r====" + node.getChildNodes().item(4).getTextContent());
                    product.setCategoryID(new BigInteger(Integer.valueOf(cateID).toString()));
                    product.setDescription(desc);
                    product.setProductImg(img);
                    product.setPrice(new BigInteger(Long.valueOf(price).toString()));
                    product.setProductID(new BigInteger(Integer.valueOf(pID).toString()));
                    product.setProductName(pName);
                    listProduct.add(product);
                }

                if (listProduct.size() == 0) {
                    request.setAttribute("searchError", "Không có sản phẩm nào cho từ khóa này.");
                    url = Constants.Search;
                } else {
                    request.setAttribute("SearchList", listProduct);
                    url = Constants.Search;
                }
            } else if (action.equals("viewdetail")) {
                int id = Integer.parseInt(request.getParameter("id"));
                String webPath = getServletContext().getRealPath("/");
                String filePath = webPath + "WEB-INF/productList.xml";
                Document doc = XMLUtils.buildDOMTree(filePath);
                XPathFactory xpf = XPathFactory.newInstance();
                XPath xpath = xpf.newXPath();

                String exp = "//product[productID = '" + id + "']";
                NodeList result = (NodeList) xpath.evaluate(exp, doc, XPathConstants.NODESET);
                List listProduct = new ArrayList();
                //List<ProductsDTO> rs = new ArrayList<ProductsDTO>();
                for (int i = 0; i < result.getLength(); i++) {
                    Node node = result.item(i);
                    String cateID = node.getChildNodes().item(1).getTextContent();
                    String desc = node.getChildNodes().item(3).getTextContent();
                    String price = node.getChildNodes().item(5).getTextContent();
                    String pID = node.getChildNodes().item(7).getTextContent();
                    String img = node.getChildNodes().item(9).getTextContent();
                    String pName = node.getChildNodes().item(11).getTextContent();
                    //TestDTO product = new TestDTO();
                    ProductList product = new ProductList();
                    //System.out.println("r====" + node.getChildNodes().item(4).getTextContent());
                    product.setCategoryID(new BigInteger(Integer.valueOf(cateID).toString()));
                    product.setDescription(desc);
                    product.setProductImg(img);
                    product.setPrice(new BigInteger(Long.valueOf(price).toString()));
                    product.setProductID(new BigInteger(Integer.valueOf(pID).toString()));
                    product.setProductName(pName);
                    listProduct.add(product);
                }
                List<CommentDTO> listComment = userDAO.CommentList(id);
                request.setAttribute("listComment", listComment);
                request.setAttribute("productDetail", listProduct);
                url = Constants.viewDetailPage;
            } else if (action.equals("accountDetail")) {
                url = Constants.accountDetailPage;
            } else if (action.equals("loadAccountDetail")) {//load personal detail
                isAjax = true;
                String info = userDAO.loadAccountDetail(user);
                response.setContentType("text/plain");
                response.setCharacterEncoding("UTF-8");
                out.write(info);
            } else if (action.equals("accountDetailInfoAjax")) {//update personal detail
                isAjax = true;
                String phone = request.getParameter("txtPhone");
                String address = request.getParameter("txtAddress");
                String info = userDAO.updateAccountDetailInfo(user, phone, address);
                response.setContentType("text/plain");
                response.setCharacterEncoding("UTF-8");
                out.write(info);
            } else if (action.equals("changePassword")) {
                isAjax = true;
                String oldPass = request.getParameter("txtOldpassword");
                String newPass = request.getParameter("txtNewpassword");
                boolean rs = userDAO.ChangePassword(user, oldPass, newPass);
                String notify = "";
                if (!rs) {
                    notify = "Mật khẩu cũ chưa chính xác. Quý khách vui lòng nhập lại;error";
                } else {
                    notify = "Đổi mật khẩu thành công";
                }
                response.setContentType("text/plain");
                response.setCharacterEncoding("UTF-8");
                out.write(notify);
            } else if (action.equals("logout")) {
                session.getAttribute("USER");
                session.getAttribute("ROLE");
                session.removeAttribute("USER");
                session.removeAttribute("ROLE");
                session.invalidate();
                url = Constants.Index;
            }
            if (!isAjax) {
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);
            }

        } catch (Exception ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
